package com.zy.hospitalward_management_system.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.hospitalward_management_system.pojo.Bed;
import com.zy.hospitalward_management_system.service.impl.BedServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zy
 * @since 2021-01-26
 */
@Controller
public class BedController {

    @Resource
    BedServiceImpl bedService;

    /**
     * 根据病房号 查询所有可用的病床
     * 可用:bed_state = 0
     * @param inpatientWardId 病房号
     * @return 可用的床位 JSON
     */
    @RequestMapping("/queryAvailableBedsByInpatientWardId")
    @ResponseBody
    public String queryAvailableBedsByInpatientWardId(int inpatientWardId){
        List<Bed> beds = bedService.getBaseMapper().selectList(new QueryWrapper<Bed>().eq("inpatientward_id", inpatientWardId).eq("bed_state", 0));
        return JSON.toJSONString(beds);
    }


    /**
     * 根据病房号,查询该病房所有的房间信息.
     * @param id 病房ID
     * @param model 携带 房间信息infos
     * @return map数组, 房间信息kv键值对
     */
    @GetMapping("/queryBedInfoByInpatientWardId/{id}")
    public String queryBedInfoByInpatientWardId(@PathVariable("id") int id, Model model){
        List<Map<String, String>> bedInfos = bedService.getBaseMapper().queryBedInfoByInpatientWardId(id);
        model.addAttribute("inpatientWardId",id);
        model.addAttribute("bedInfos",bedInfos);
        return "user/list/bed_list";
    }

    /**
     * 根据病房号 添加床位
     * @param inpatientWardId 病房号
     * @return ajax 返回 信息提示
     */
    @GetMapping("/addBedByInpatientWardId")
    @ResponseBody
    public String addBedByInpatientWardId(String inpatientWardId){
        Integer bedCounts = bedService.getBaseMapper().selectCount(new QueryWrapper<Bed>().eq("inpatientward_id", inpatientWardId));
        if(bedCounts==6){
            return "不能再添加更多床位了!";
        }
        Bed bed = new Bed(null,0,Integer.parseInt(inpatientWardId));
        int insert = bedService.getBaseMapper().insert(bed);
        if(insert==1){
            return "添加成功!";
        }else {
            return "添加失败!";
        }
    }


    @RequestMapping("/deleteBedByBedId/{inpatientWardId}/{bedId}")
    public String deleteBedByBedId(@PathVariable("inpatientWardId") String inpatientWardId,@PathVariable("bedId") String bedId){
        int i = bedService.getBaseMapper().deleteById(bedId);
        return "redirect:/queryBedInfoByInpatientWardId/"+inpatientWardId;
    }
}

